package com.wx.house.manager.api.statistics.services.impl;

import com.wx.house.common.util.StringUtil;
import com.wx.house.core.mapper.statistics.ExpenseStatisticsMapper;
import com.wx.house.core.pojo.vo.expenseStatistics.ExpenseMonthDetailStatisticsVo;
import com.wx.house.core.pojo.vo.expenseStatistics.ExpenseMonthStatisticsVo;
import com.wx.house.core.pojo.vo.expenseStatistics.ExpenseYearStatisticsVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import com.wx.house.manager.api.statistics.services.ExpenseStatisticsServices;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @Author ：罗棋
 * @Email ：58428467@qq.com
 * @date ：Created in 2019/12/13 下午 02:06 @description：
 * @version: ：V
 */
@Service
@RequiredArgsConstructor
public class ExpenseStatisticsServicesImpl implements ExpenseStatisticsServices {
	private final ExpenseStatisticsMapper expenseStatisticsMapper;

	@Override
	public List<ExpenseYearStatisticsVo> selectExpenseYearStatisticsVo(String maccid, String year) {
		// 如果查询到年份的结果才开始填充数据
		return IntStream.range(1, 13).boxed().map(i -> {
			List<ExpenseYearStatisticsVo> collect = expenseStatisticsMapper.selectExpenseYearStatisticsVo(maccid, year)
					.stream().filter(e -> Integer.parseInt(e.getTime().split("-")[1]) == i)
					.collect(Collectors.toList());
			// 如果当月有数据，否则就开始伪造数据
			return collect.size() >= 1 ? collect.get(0)
					: new ExpenseYearStatisticsVo(
							(StringUtil.isEmpty(year) ? new SimpleDateFormat("yyyy").format(new Date()) : year) + "-"
									+ i,
							new BigDecimal(0), new BigDecimal(0));
		}).collect(Collectors.toList());
	}

	@Override
	public ExpenseMonthStatisticsVo selectExpenseMonthStatisticsVo(String maccid, String yearMonth) {
		yearMonth = StringUtil.isEmpty(yearMonth) ? new SimpleDateFormat("yyyy-MM").format(new Date()) : yearMonth;
		ExpenseMonthStatisticsVo expenseMonthStatisticsVo = expenseStatisticsMapper
				.selectExpenseMonthStatisticsVo(maccid, yearMonth);
		if (expenseMonthStatisticsVo == null)
			expenseMonthStatisticsVo = new ExpenseMonthStatisticsVo();

		ExpenseMonthStatisticsVo finalExpenseMonthStatisticsVo = expenseMonthStatisticsVo;
		expenseMonthStatisticsVo.setDetailStatisticsVoList(IntStream.range(0, 6).boxed().map(i -> {
			List<ExpenseMonthDetailStatisticsVo> collect = finalExpenseMonthStatisticsVo.getDetailStatisticsVoList()
					.stream().filter(e -> e.getExpenseType().equals(i)).collect(Collectors.toList());
			return collect.size() >= 1 ? collect.get(0)
					: new ExpenseMonthDetailStatisticsVo(i, new BigDecimal(0), new BigDecimal(0));
		}).collect(Collectors.toList()));
		expenseMonthStatisticsVo.setTime(yearMonth);
		return expenseMonthStatisticsVo;
	}
}
